package com.hs.bai.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hs.bai.pojo.*;
import com.hs.bai.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.dto.PageBean;
import com.hs.dto.ResultBean;
import lombok.val;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Dingkun Bai
 * @since 2022-06-13
 */
@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    /**
     * 分页查询
     * @param id 订单编号
     * @param customerName 客户名称
     * @param departureCity 出发城市
     * @param destinationCity 目的城市
     * @param currentPage 当前页面数
     * @param pageSize 当前页面条数
     * @param orderStatus 订单状态
     * @return
     */
    @GetMapping("/page")
    public ResultBean findAllByPage(@RequestParam(required = false) String id, @RequestParam(required = false) String customerName, @RequestParam(required = false) String departureCity, @RequestParam(required = false) String destinationCity, @RequestParam Integer orderStatus, @RequestParam Integer currentPage, @RequestParam Integer pageSize){

        IPage<Order> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Order> qw = new QueryWrapper<>();
        //设置订单状态
        qw.eq("order_status",orderStatus);
        //判断条件是否为空
        if (StringUtils.hasText(id)) {
            qw.eq("id",id);
        }
        if (StringUtils.hasText(customerName)) {
            qw.eq("customer_name",customerName);
        }
        if (StringUtils.hasText(departureCity)) {
            qw.eq("departure_city",departureCity);
        }
        if (StringUtils.hasText(destinationCity)) {
            qw.eq("destination_city",destinationCity);
        }
        //查询
        val orderIPage = orderService.page(page, qw);

        PageBean<Order> pageBean = new PageBean<>();
        if (orderIPage != null) {

            pageBean.setList(orderIPage.getRecords());
            pageBean.setTotal((int) orderIPage.getTotal());
            val resultBean = ResultBean.OK();
            resultBean.setData(pageBean);
            return resultBean;

        }
        return ResultBean.ERROR();

    }

    /**
     * 根据id实时查询数据库
     * @param id
     * @return
     */
    @GetMapping("/judge/{id}")
    public ResultBean judgeById(@PathVariable String id){
        Order order = orderService.getById(id);
        if (order != null) {
            return ResultBean.ERROR("已有该订单");
        }
        return ResultBean.OK();
    }

    /**
     * 根据id查询订单
     * @param id
     * @return
     */
    @GetMapping("/find/{id}")
    public ResultBean findById(@PathVariable String id){
        Order order = orderService.getById(id);
        if (order != null){
            ResultBean ok = ResultBean.OK();
            ok.setData(order);
            return ok;
        }
        return ResultBean.ERROR();
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public ResultBean deleteByIds(@RequestBody List<String> ids){

        System.out.println("ids = " + ids);

        if (CollectionUtils.isEmpty(ids)) {
            return ResultBean.ERROR("请先选择数据！");
        }

        return orderService.deleteAllInfo(ids);

    }

    /**
     * 订单提交
     * @param id
     * @return
     */
    @GetMapping("/submit/{id}")
    public ResultBean updateStatus(@PathVariable String id){

        UpdateWrapper<Order> uw = new UpdateWrapper<>();
        uw.set("order_status",1);
        uw.eq("id",id);
        boolean b = orderService.update(uw);
        return b ? ResultBean.OK("提交成功！"):ResultBean.ERROR("提交失败！");
    }

    /**
     * 导出excel
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/down")
    public void down(@RequestParam Integer currentPage, @RequestParam Integer pageSize,HttpServletResponse resp) throws IOException {

        IPage<Order> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Order> qw = new QueryWrapper<>();
        //查询
        val orderIPage = orderService.page(page, qw);

        if (orderIPage != null) {
            downLoad(orderIPage.getRecords(),resp);
        }
    }

    /**
     * 导出
     */
    private void downLoad(List<Order> list,HttpServletResponse resp) throws IOException {

        Workbook wb = new HSSFWorkbook();

        val sheet = wb.createSheet("订单列表");

        val row = sheet.createRow(0);

        val aClass = Order.class;
        val fields = aClass.getDeclaredFields();

        for (int i = 0; i < fields.length; i++) {

            String s = fields[i].toString();
            row.createCell(i).setCellValue(s.substring(s.lastIndexOf('.')+1));

        }

        for (int i = 0; i < list.size(); i++) {

            val row1 = sheet.createRow(i + 1);

            val order = list.get(i);

            row1.createCell(1).setCellValue(order.getId());
            row1.createCell(2).setCellValue(order.getTAId());
            row1.createCell(3).setCellValue(order.getOrderType());
            row1.createCell(4).setCellValue(order.getTransType());
            row1.createCell(5).setCellValue(order.getCustomerName());
            row1.createCell(6).setCellValue(order.getOrderTime());
            row1.createCell(7).setCellValue(order.getDepartureCity());
            row1.createCell(8).setCellValue(order.getDestinationCity());
            row1.createCell(9).setCellValue(order.getOrderStatus());
            row1.createCell(10).setCellValue(order.getTFId());
            row1.createCell(11).setCellValue(order.getTRId());
            row1.createCell(12).setCellValue(order.getDeleted());

        }

        //设置一个头信息   让浏览器 把回写的文件保存到 本地

        resp.setHeader("content-disposition","attachment;filename=order.xls");

        wb.write(resp.getOutputStream());
        wb.close();
    }


}
